package com.example.turingim.handler;

import com.alibaba.fastjson.JSON;
import com.example.turingim.common.CommandType;
import com.example.turingim.common.ResponseResult;
import com.example.turingim.dto.Command;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame)
            throws Exception {
        try {
            Command command = JSON.parseObject(frame.text(), Command.class);
            switch (CommandType.match(command.getCode())) {
                case CONNECTION:
                    ConnectionHandler.execute(ctx, command);
                    break;
                case CHAT:
                    ChatHandler.execute(ctx, frame);
                    break;
                case JOIN_GROUP:
                    JoinGroupHandler.execute(ctx);
                    break;
                default:
                    ctx.channel().writeAndFlush(ResponseResult.fail("不支持的CODE"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(ResponseResult.fail(e.getMessage()));
        }
    }
}
